package com.example.lxc415billiards.controller;


import com.example.lxc415billiards.exception.BizException;
import com.example.lxc415billiards.untils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@RestController
@Api(tags = "文件上传接口")
@RequestMapping("/file")
public class FileController {

    @Value("${RuoYi.profile}")
    private String UPLOD_FOLDER;
    @ApiOperation(value = "文件上传",notes = "本地文件上传到服务器")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart("file") MultipartFile file) throws IOException {
        if (file.isEmpty()){
            return AjaxResult.error("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        File path = new File(UPLOD_FOLDER);
        if (!path.exists()){
            path.mkdirs();
        }
        File dest = new File(UPLOD_FOLDER +"/"+ fileName);
        try {
            file.transferTo(dest);
            String url = "/private/" + fileName;
            return AjaxResult.success("上传成功").put("url",url);
        }catch (IOException e)
        {
            throw  new BizException(500,"上传失败");
        }
    }
}
